<template>
  <div class="container">
    <el-form ref="refForm" :rules="rules" :model="form" label-width="80px">
      <el-form-item label="标签名称" prop="tagName">
        <el-input v-model="form.tagName" />
      </el-form-item>
      <el-form-item v-if="!breadName" label="所属学科">
        <el-select v-model="form.subjectID" placeholder="请选择">
          <el-option v-for="item in subjectName" :key="item.id" :label="item.subjectName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="hSubmit">确认</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { add, update, detail } from '@/api/hmmm/tags'
import { list } from '@/api/hmmm/subjects'
export default {
  props: {
    breadName: {
      type: String,
      default: null
    },
    subjectID: {
      type: Number,
      default: null
    },
    isEdit: {
      type: Boolean,
      default: null
    },
    curId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      form: {
        tagName: '',
        subjectID: this.subjectID || null
      },
      rules: {
        tagName: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      subjectName: []
    }
  },
  created() {
    this.fetchSubjectName()
  },
  methods: {
    // 提交
    hSubmit() {
      this.$refs.refForm.validate((valid) => {
        valid && (this.isEdit ? this.doEdit() : this.doAdd())
      })
    },
    // 编辑
    async doEdit() {
      await update({ id: this.curId, ...this.form })
      this.$emit('close')
    },
    // 添加
    async doAdd() {
      const res = await add(this.form)
      console.log(res)
      this.$emit('close')
    },
    // 重置表单
    reset() {
      this.form = {
        tagName: '',
        id: null
      }
      this.$refs.refForm.resetFields()
    },
    // 取消关闭弹窗
    close() {
      this.$emit('close')
    },
    // 获取目录名
    async fetchSubjectName() {
      const res = await list()
      this.subjectName = res.data.items
      // 数据回填
      if (this.isEdit) {
        const rs = await detail({ id: this.curId })
        this.form.tagName = rs.data.tagName
      }
    }
  }
}
</script>

<style scoped lang='less'></style>
